<?php

/**
 * @Author:      zwh
 * @DateTime:    2016-11-9 10:55:13
 * @Description: 保险业务
 */
class ScsInsuranceController extends BaseController
{
    
    /**
     * @Author:      lyt
     * @DateTime:  2017-05-23 10:43:24
     * @Description: 用户的保险充值
     */
    public function recharge(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'user_id' => 'required',
                'id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }
            //传入参数      
            $token=Input::get("token");      
            $user_id=Input::get("user_id");
            $id_card=Input::get("id_card");
            $id=Input::get("id");
            $have_card = Input::get("have_card",0); //是否有用户身份信息
            //传入参数
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            $insurance=Insurance::find(Input::get('id'));

            if(is_null($insurance)||$insurance->status!=1){
                $response = Lang::get("scs_error.insurance_notexiet_90005");
                break;
            }

            if($insurance->website!=$sc_user->shop_id){
                $response = Lang::get("scs_error.insurance_shop_notexiet_90019");
                break;
            }
            $date=date("Y-m-d 00:00:00",strtotime("-1 month"));
            if($insurance->bill_time<$date){
                $response = Lang::get("scs_error.insurance_time_error_90023");
                break;
            }
            $amount=0;
            if($insurance->is_decide==0){
                if($insurance->kickback_amount_type==1){
                    $amount+=$insurance->kickback_amount;
                }
                if($insurance->jq_amount_type==1){
                    $amount+=$insurance->jq_amount;
                }
                if($insurance->cc_amount_type==1){
                    $amount+=$insurance->cc_amount;
                }
                $amount=ceil($amount/100)*100;
            }else{//自定义的设位
                $amount=bcdiv($insurance->recharge_amount,100,0)*100;
            }
            if($amount<=0){//说明不能充值
                $response = Lang::get("scs_error.insurance_amount_error_90018");
                break;
            }
            // $kr=KickbackRate::find($insurance->kickback_rate);
            // if($insurance->kickback_amount<=0||is_null($kr)||$kr->is_rechange==0){//说明不能充值
            //     $response = Lang::get("scs_error.insurance_amount_error_90018");
            //     break;
            // }
            $a_in=AcountInsurance::find(Input::get('id'));
            if($a_in){
                $response = Lang::get("scs_error.insurance_rechange_exits_90017");
                break;
            }

            $user=Users::where("id",$user_id)->where("status",1)->first();
            if(is_null($user)){
                $response = Lang::get("scs_error.order_user_notexit_error_40097");
                break;
            }
            //检查身份证后四位
            if($user->type==1){//个人用户判断身份证
                if (!$have_card) {
                    $temp_u=Users::where("id_card",$insurance->identity_card)->first();
                    if($temp_u){
                        $response = Lang::get("scs_error.order_user_id_card_error_40132");
                        break;
                    }
                    
                    $id_card = $insurance->identity_card;
                    if(preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $id_card)){
                        $user->id_card = $id_card;
                        $user->save();
                    }else {
                        $response = Lang::get("scs_error.order_user_id_card_error_40098");
                        break;
                    }

                    
                }else{
                    if(is_null($id_card)||strlen($id_card)!=4){
                        $response = Lang::get("scs_error.order_user_id_card_error_40098");
                        break;
                    }else{
                        if((substr($user->id_card,-4)!=$id_card)){
                            $response = Lang::get("scs_error.order_user_id_card_error_40098");
                            break;
                        }
                    }   
                }         
            }
            else{//用户名密码判断 组织机构代码验证 有就算有
                // $sc=SCUser::where('user_name',$user_name)->where('password',strtoupper(md5($pass_word)))->where('status',1)->first();
                // if(is_null($sc)||$sc->shop_id!=$sc_user->shop_id){
                //     $response = Lang::get("scs_error.scs_user_not_exiet21009");
                //     break;
                // }
                // if($sc->title!=1){
                //     $response = Lang::get("scs_error.login_user_error_21016");
                //     break;
                // }
                $c=Companys::find($user->id);
                if(is_null($c)||!$c->identification_number){
                    $response = Lang::get("scs_error.order_user_id_card_error_40099");
                    break;
                }
            }
            $response=AcountInsurance::rechange($id,$user_id,$sc_user,$id_card,$amount);
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "account", "event" => "recharge", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      zwh
     * @DateTime:    2016-11-9 14:41:32
     * @Description: 保险单详情
     */
    public function show(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $insurance=Insurance::find(Input::get('id'));

            if(is_null($insurance)){
                $response = Lang::get("scs_error.insurance_notexiet_90005");
                break;
            }

            //添加打印次数
            if (Input::get('print_num') != '') {
                $tmp = $insurance;
                $tmp->print_num += 1;
                try {
                    $tmp->save();
                } catch (Exception $e) {
                    $response = Lang::get("scs_error.insurance_notexiet_900051");
                    break;
                }
            }

            if($insurance->insurance_type==1){//交强险
                $traffic_accident_insurance=InsuranceDetail::where('insurance_id',$insurance->id)->where('type',1)->first();
                if($traffic_accident_insurance){
                    $traffic_accident_insurance->amount=bcdiv($traffic_accident_insurance->amount,100,2);
                    $traffic_accident_insurance->use_tax=bcdiv($traffic_accident_insurance->use_tax,100,2);

                    if (!empty($traffic_accident_insurance->jq_rule)) {
                        $traffic_accident_insurance->jq_kr_id = $traffic_accident_insurance->jq_rule;
                        $jq_kr_info = KickbackRate::rateInfo($traffic_accident_insurance->jq_rule,1);
                        $traffic_accident_insurance->jq_kr_name = $jq_kr_info->name;
                    }else{
                        $traffic_accident_insurance->jq_kr_name = "";
                        $traffic_accident_insurance->jq_kr_id = "";
                    }
                    
                    if (!empty($traffic_accident_insurance->cc_rule)) {
                        $traffic_accident_insurance->cc_kr_id = $traffic_accident_insurance->cc_rule;
                        $cc_kr_info = KickbackRate::rateInfo($traffic_accident_insurance->cc_rule,2);
                        $traffic_accident_insurance->cc_kr_name = $cc_kr_info->name;
                    }else{
                        $traffic_accident_insurance->cc_kr_name = "";
                        $traffic_accident_insurance->cc_kr_id = "";
                    }
                    $commercial_insurance=new stdClass();
                }else{
                    $commercial_insurance=$traffic_accident_insurance=new stdClass();
                }
            }else if($insurance->insurance_type==2){//商业险
                $commercial_insurance=InsuranceDetail::where('insurance_id',$insurance->id)->where('type',2)->first();
                if($commercial_insurance){
                    $its=InsuranceTypes::where('insurance_detail_id',$commercial_insurance->id)->get();
                    $commercial_insurance->its=$its;
                    $commercial_insurance->amount=bcdiv($commercial_insurance->amount,100,2);

                    if(!empty($commercial_insurance->sy_rule)){
                        $commercial_insurance->sy_kr_id = $commercial_insurance->sy_rule;
                        $sy_kr_info = KickbackRate::rateInfo($commercial_insurance->sy_rule,3);
                        $commercial_insurance->sy_kr_name = $sy_kr_info->name;
                    }else{
                        $commercial_insurance->sy_kr_id = "";
                        $commercial_insurance->sy_kr_name = "";
                    }

                    $traffic_accident_insurance=new stdClass();
                }else{
                    $commercial_insurance=$traffic_accident_insurance=new stdClass();
                }
            }else{//交强险与商业险
                $traffic_accident_insurance=InsuranceDetail::where('insurance_id',$insurance->id)->where('type',1)->first();
                if($traffic_accident_insurance){
                    $traffic_accident_insurance->amount=bcdiv($traffic_accident_insurance->amount,100,2);
                    $traffic_accident_insurance->use_tax=bcdiv($traffic_accident_insurance->use_tax,100,2);

                    if (!empty($traffic_accident_insurance->jq_rule)) {
                        $traffic_accident_insurance->jq_kr_id = $traffic_accident_insurance->jq_rule;
                        $jq_kr_info = KickbackRate::rateInfo($traffic_accident_insurance->jq_rule,1);
                        $traffic_accident_insurance->jq_kr_name = $jq_kr_info->name;
                    }else{
                        $traffic_accident_insurance->jq_kr_id = "";
                        $traffic_accident_insurance->jq_kr_name = "";
                    }

                    if (!empty($traffic_accident_insurance->cc_rule)) {
                        $traffic_accident_insurance->cc_kr_id = $traffic_accident_insurance->cc_rule;
                        //echo $traffic_accident_insurance->type;die;
                        $cc_kr_info = KickbackRate::rateInfo($traffic_accident_insurance->cc_rule,2);
                        $traffic_accident_insurance->cc_kr_name = $cc_kr_info->name;
                    }else{
                        $traffic_accident_insurance->cc_kr_id = "";
                        $traffic_accident_insurance->cc_kr_name = "";
                    }
                }else{
                    $traffic_accident_insurance=new stdClass();
                }
                $commercial_insurance=InsuranceDetail::where('insurance_id',$insurance->id)->where('type',2)->first();
                if($commercial_insurance){
                    $its=InsuranceTypes::where('insurance_detail_id',$commercial_insurance->id)->get();
                    foreach($its as $_its){
                        $_its->amount=bcdiv($_its->amount,100,2);
                    }
                    $commercial_insurance->its=$its;
                    $commercial_insurance->amount=bcdiv($commercial_insurance->amount,100,2);

                    if(!empty($commercial_insurance->sy_rule)){
                        $commercial_insurance->sy_kr_id = $commercial_insurance->sy_rule;
                        $sy_kr_info = KickbackRate::rateInfo($commercial_insurance->sy_rule,3);
                        $commercial_insurance->sy_kr_name = $sy_kr_info->name;
                    }else{
                        $commercial_insurance->sy_kr_id = "";
                        $commercial_insurance->sy_kr_name = "";
                    }
                }else{
                    $commercial_insurance=new stdClass();
                }
            }
            $ms=MaintenanceShops::find($insurance->website);
            $insurance->website_name=$ms->name;
            $insurance->traffic_accident_insurance=$traffic_accident_insurance;
            $insurance->commercial_insurance=$commercial_insurance;
            $insurance->amount=bcdiv($insurance->amount,100,2);
            $insurance->purchase_amount=bcdiv($insurance->purchase_amount,100,2);
            $insurance->kickback_amount=bcdiv($insurance->kickback_amount,100,2);
            $insurance->jq_amount=bcdiv($insurance->jq_amount,100,2);
            $insurance->cc_amount=bcdiv($insurance->cc_amount,100,2);
            if ($insurance->is_decide == 1) { //如果是自定义的值，直接返回自定义的值 自定义的设位
                $insurance->cash = bcdiv($insurance->cash_amount,100,0);
                $insurance->recharge = bcdiv($insurance->recharge_amount,100,0);
            } else {//正常返现比例 相加进1 
                $insurance->cash = 0;
                $insurance->recharge = 0;
                //计算现金和充值总计 0现金  1充值
                if($insurance->kickback_amount_type == 0){
                    $insurance->cash += $insurance->kickback_amount;
                }else{
                    $insurance->recharge += $insurance->kickback_amount;
                }

                if($insurance->jq_amount_type == 0){
                    $insurance->cash += $insurance->jq_amount;
                }else{
                    $insurance->recharge += $insurance->jq_amount;
                }

                if($insurance->cc_amount_type == 0){
                    $insurance->cash += $insurance->cc_amount;
                }else{
                    $insurance->recharge += $insurance->cc_amount;
                }
                $insurance->cash = ceil($insurance->cash);
                $insurance->recharge = ceil($insurance->recharge);
            }

            
            $ai=AcountInsurance::leftJoin("users","users.id","=","acount_insurance_record.user_id")->
            leftJoin("sc_user","sc_user.id","=","acount_insurance_record.created_by")
            ->where("acount_insurance_record.id",$insurance->id)
            ->select("sc_user.real_name as sc_user_name","sc_user.id as sc_user_id","acount_insurance_record.implement_time","users.real_name as user_name","users.id as user_id","users.phone as user_phone")->first();
            $ai_array=array(
                "user_id"=>isset($ai)?$ai->user_id:'',
                "user_name"=>isset($ai)?$ai->user_name:'',
                "user_phone"=>isset($ai)?$ai->user_phone:'',
                "sc_user_name"=>isset($ai)?$ai->sc_user_name:'',
                "sc_user_id"=>isset($ai)?$ai->sc_user_id:'',
                "implement_time"=>isset($ai)?$ai->implement_time:'',
            );
            
            $kickback_list = KickbackRate::leftJoin("kickback_shop","kickback_shop.kickback_id","=","kickback_rate.id")
                                ->leftJoin("kickback_config","kickback_config.id","=","kickback_rate.con_id")
                                ->where("kickback_shop.shop_id",$sc_user->shop_id)
                                ->where("kickback_rate.status",1)
                                ->select("kickback_rate.*", "kickback_config.math")
                                ->get();
            $kr_type = KickbackRate::$type;
            $kr_list = [1=>[],2=>[],3=>[]];
            foreach ($kickback_list as $v) {
                $kr_list[$v->type][] = $v->toarray();
            }
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('insurance'=>$insurance,"ai_info"=>$ai_array,"kr_list"=>$kr_list,"kr_type"=>$kr_type));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "order_show", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-10-12 11:34:18
     * @Description: 
     */
    public function create(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'car_no' => 'required',
                //'website' => 'required',
                'engine_number' => 'required',
                'model' => 'required',
                'vin' => 'required',
                'use_nature' => 'required',
                'purchase_amount' => 'required',
                'register_time' => 'required',
                'species' => 'required',
                'owner' => 'required',
                'insurance_owner' => 'required',
                'type' => 'required',
                'identity_card' => 'required',
                'phone' => 'required',
                'operator_type' => 'required',
                'operator_id' => 'required',
                'referrer_type' => 'required',
                'referrer' => 'required',
                'accept_insurance_id' => 'required',
                'bill_time' => 'required',
                'insurance_type' => 'required',
                'is_renewal_insurance'=>"required|in:1,0",
                //'kickback_rate' => 'required',
                //'kickback_amount' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $id=Common::createOrderId();
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $insurance=new Insurance;
            $insurance->id=$id;
            $insurance->car_no=Input::get('car_no');
            $insurance->website=$sc_user->shop_id;
            $insurance->engine_number=Input::get('engine_number');
            $insurance->model=Input::get('model');
            $insurance->vin=Input::get('vin');
            $insurance->use_nature=Input::get('use_nature');
            $insurance->purchase_amount=bcmul(Input::get('purchase_amount'),100);
            $insurance->register_time=Input::get('register_time');
            $insurance->species=Input::get('species');
            $insurance->owner=Input::get('owner');
            $insurance->insurance_owner=Input::get('insurance_owner');
            $insurance->type=Input::get('type');
            $insurance->identity_card=Input::get('identity_card');
            $insurance->phone=Input::get('phone');
            $insurance->operator_type=Input::get('operator_type');
            $insurance->operator_id=Input::get('operator_id');
            $insurance->referrer_type=Input::get('referrer_type');
            $insurance->referrer=Input::get('referrer');
            $insurance->accept_insurance_id=Input::get('accept_insurance_id');
            $insurance->bill_time=Input::get('bill_time');
            $insurance->insurance_type=Input::get('insurance_type');
            $insurance->is_renewal_insurance=Input::get('is_renewal_insurance');
            $insurance->save();
            $response['result']=array('id'=>$id);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "create", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      zwh
     * @DateTime:    2016-11-9 14:23:18
     * @Description: 更新保险单
     */
    public function update(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
                'car_no' => 'required',
                //'website' => 'required',
                'engine_number' => 'required',
                'model' => 'required',
                'vin' => 'required',
                'use_nature' => 'required',
                'purchase_amount' => 'required',
                'register_time' => 'required',
                'species' => 'required',
                'owner' => 'required',
                'insurance_owner' => 'required',
                'type' => 'required',
                'identity_card' => 'required',
                'identity_card' => 'required',
                'phone' => 'required',
                'operator_type' => 'required',
                'operator_id' => 'required',
                'referrer_type' => 'required',
                'referrer' => 'required',
                'accept_insurance_id' => 'required',
                'bill_time' => 'required',
                'insurance_type' => 'required',
                'is_renewal_insurance'=>"required|in:1,0",
                'is_decide'=>"required|in:1,0",
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            DB::beginTransaction();
            $insurance=Insurance::find(Input::get('id'));
            if(is_null($insurance)){
                $response = Lang::get("scs_error.insurance_notexiet_90005");
                break;
            }
            $falg=true;//是否能编辑价格 默认是 充值之后变为false
            $a_in=AcountInsurance::find(Input::get('id'));
            if($a_in){
                $falg=false;
            }
            $insurance->car_no=Input::get('car_no');
            $insurance->website=$sc_user->shop_id;
            $insurance->engine_number=Input::get('engine_number');
            $insurance->model=Input::get('model');
            $insurance->vin=Input::get('vin');
            $insurance->use_nature=Input::get('use_nature');
            $insurance->purchase_amount=bcmul(Input::get('purchase_amount'),100);
            $insurance->register_time=Input::get('register_time');
            $insurance->species=Input::get('species');
            $insurance->owner=Input::get('owner');
            $insurance->insurance_owner=Input::get('insurance_owner');
            $insurance->type=Input::get('type');
            $insurance->identity_card=Input::get('identity_card');
            $insurance->phone=Input::get('phone');
            $insurance->operator_type=Input::get('operator_type');
            $insurance->operator_id=Input::get('operator_id');
            $insurance->referrer_type=Input::get('referrer_type');
            $insurance->referrer=Input::get('referrer');
            $insurance->accept_insurance_id=Input::get('accept_insurance_id');
            $insurance->bill_time=Input::get('bill_time'); 
            $insurance->is_decide=Input::get('is_decide');  
            if($falg){//如果充值了不让编辑
                $insurance->insurance_type=Input::get('insurance_type');
                $insurance->kickback_rate=Input::get('kickback_rate');
                if($insurance->is_decide) {
                    $insurance->cash_amount = bcmul(Input::get('cash'),100);
                    $insurance->recharge_amount = bcmul(Input::get('recharge'),100);
                }
            }
            
            $insurance->is_renewal_insurance=Input::get('is_renewal_insurance');
            $insurance->save();
            $commercial_insurance_amount=0;
            $commercial_insurance=InsuranceDetail::where('insurance_id',Input::get('id'))->where('type',2)->first();
            
            if($commercial_insurance){//存在商业险
                $old_detail_sy_amount = $commercial_insurance->sy_amount;
                $old_detail_sy_rule = $commercial_insurance->sy_rule;
                $commercial_insurance_amount=$commercial_insurance->amount;
                InsuranceTypes::where('insurance_detail_id',$commercial_insurance->id)->delete();
            }
            $jq_commercial_insurance_amount=$jq_commercial_insurance_use_tax=0;
            $jq_commercial_insurance=InsuranceDetail::where('insurance_id',Input::get('id'))->where('type',1)->first();
            if($jq_commercial_insurance){//存在交强险
                $old_detail_jq_amount = $jq_commercial_insurance->jq_amount;
                $old_detail_jq_rule = $jq_commercial_insurance->jq_rule;
                $old_detail_cc_amount = $jq_commercial_insurance->cc_amount;
                $old_detail_cc_rule = $jq_commercial_insurance->cc_rule;
                $jq_commercial_insurance_amount=$jq_commercial_insurance->amount;
                $jq_commercial_insurance_use_tax=$jq_commercial_insurance->use_tax;                
            }
            InsuranceDetail::where('insurance_id',Input::get('id'))->delete();
            $traffic_accident_insurance=json_decode(Input::get('traffic_accident_insurance'),1);
            $commercial_insurance=json_decode(Input::get('commercial_insurance'),1);
            
            $amount=0;//保险总金额
            $commercial_amount=0;//商业保险金额
            if($insurance->insurance_type==1 || $insurance->insurance_type== 3){
                if(Input::get('traffic_accident_insurance')){
                    $insurance_detail=new InsuranceDetail;
                    $insurance_detail->insurance_id=$insurance->id;
                    $insurance_detail->type=1;
                    $insurance_detail->policy_no=$traffic_accident_insurance['policy_no'];
                    $insurance_detail->start_time=$traffic_accident_insurance['start_time'];
                    $insurance_detail->end_time=$traffic_accident_insurance['end_time'];
                    $insurance_detail->amount=$falg?bcmul($traffic_accident_insurance['amount'],100):$jq_commercial_insurance_amount;
                    $insurance_detail->use_tax=$falg?bcmul($traffic_accident_insurance['use_tax'],100):$jq_commercial_insurance_use_tax;
                    if ($falg) {
                        //返现金额
                        if (!empty($traffic_accident_insurance['jq_kr_id']) && !$insurance->is_decide) {  //如果没有返现规则id， 或者 是指定返现金额的，这些值都不进行规则计算
                            //注意计算之前，金额不要扩大100倍。因为公式内可能会有加减
                            $jq_amount = KickbackRate::amountInfo($traffic_accident_insurance['amount'], $traffic_accident_insurance['jq_kr_id']);
                            if (!$jq_amount) {
                                $response = Lang::get("scs_error.kr_status_error_90024");
                                break;
                            }
                            $insurance_detail->jq_amount = bcmul(round($jq_amount["amount"]),100);
                            $insurance_detail->jq_rule = $traffic_accident_insurance['jq_kr_id'];
                            $insurance->jq_amount = bcmul(round($jq_amount["amount"]),100);
                            $insurance->jq_amount_type = $jq_amount["is_rechange"];
                        }else { //如果没有传值
                            $insurance_detail->jq_amount = 0;
                            $insurance_detail->jq_rule = 0;
                            $insurance->jq_amount = 0;
                            $insurance->jq_amount_type = 0;
                        }
                        if (!empty($traffic_accident_insurance['cc_kr_id'])  && !$insurance->is_decide) {
                            $cc_amount = KickbackRate::amountInfo($traffic_accident_insurance['use_tax'], $traffic_accident_insurance['cc_kr_id']);
                            if (!$cc_amount) {
                                $response = Lang::get("scs_error.kr_status_error_90024");
                                break;
                            }
                            $insurance_detail->cc_amount = bcmul(round($cc_amount["amount"]),100);
                            $insurance_detail->cc_rule = $traffic_accident_insurance['cc_kr_id'];
                            $insurance->cc_amount = bcmul(round($cc_amount["amount"]),100);
                            $insurance->cc_amount_type = $cc_amount["is_rechange"];
                        }else{
                            $insurance_detail->cc_amount = 0;
                            $insurance_detail->cc_rule = 0;
                            $insurance->cc_amount = 0;
                            $insurance->cc_amount_type = 0;
                        }
                    }else{ //如果充值过后，再进入这个方法，会重新定义详情，所以，之前历史的值需要通过这种方式保留
                            $insurance_detail->jq_amount = $old_detail_jq_amount;
                            $insurance_detail->jq_rule = $old_detail_jq_rule;
                            $insurance_detail->cc_amount = $old_detail_cc_amount;
                            $insurance_detail->cc_rule = $old_detail_cc_rule;
                    }

                    $insurance_detail->save();
                    $amount+=$insurance_detail->amount;
                    $amount+=$insurance_detail->use_tax;
                }
            }
            if($insurance->insurance_type==2 || $insurance->insurance_type== 3){
                if(Input::get('commercial_insurance')){
                    $insurance_detail=new InsuranceDetail;
                    $insurance_detail->insurance_id=$insurance->id;
                    $insurance_detail->type=2;
                    $insurance_detail->policy_no=$commercial_insurance['policy_no'];
                    $insurance_detail->start_time=$commercial_insurance['start_time'];
                    $insurance_detail->end_time=$commercial_insurance['end_time'];
                    $insurance_detail->amount=$falg?bcmul($commercial_insurance['amount'],100):$commercial_insurance_amount;
                    if($falg){
                        if (!empty($commercial_insurance['sy_kr_id'])  && !$insurance->is_decide) {
                            $sy_amount = KickbackRate::amountInfo($commercial_insurance['amount'], $commercial_insurance['sy_kr_id']);
                            if (!$sy_amount) {
                                $response = Lang::get("scs_error.kr_status_error_90024");
                                break;
                            }
                            $insurance_detail->sy_amount = bcmul(round($sy_amount["amount"]),100);
                            $insurance_detail->sy_rule = $commercial_insurance['sy_kr_id'];
                            $insurance->kickback_amount = bcmul(round($sy_amount["amount"]),100);
                            $insurance->kickback_amount_type = $sy_amount["is_rechange"];
                        }else {
                            $insurance_detail->sy_amount = 0;
                            $insurance_detail->sy_rule = 0;
                            $insurance->kickback_amount = 0;
                            $insurance->kickback_amount_type = 0;
                        }
                    }else{
                            $insurance_detail->sy_amount = $old_detail_sy_amount;
                            $insurance_detail->sy_rule = $old_detail_sy_rule;
                    }

                    
                    $insurance_detail->car_damage=$commercial_insurance['car_damage'];
                    $insurance_detail->save();
                    foreach($commercial_insurance['its'] as $item){
                        $insurance_types=new InsuranceTypes;
                        $insurance_types->insurance_detail_id=$insurance_detail->id;
                        $insurance_types->insurance_type=$item['type'];
                        //$insurance_types->coverage=$item['coverage'];
                        $insurance_types->amount=bcmul($item['amount'],100);
                        $insurance_types->save();                    
                    }
                    $amount+=$insurance_detail->amount;
                }  
            }
            if ($insurance->cash_amount+$insurance->recharge_amount > $amount){
                DB::rollback();
                $response = Lang::get("scs_error.insurance_amount_error_90025");
                break;
            }
            
            if($falg){
                $insurance->amount=$amount;
            }    
            $insurance->save();
            DB::commit();
            $response['result']=array('id'=>Input::get('id'));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "update", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      zwh
     * @DateTime:    2016-11-10 10:21:30
     * @Description: 保险单列表
     */
    public function lists(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $insurances=array();
            $car_no = Input::get('car_no');
            $page = Input::get('page');
            $page_size = Input::get('page_size');
            $count = 0;
            if($car_no){
                $insurances=Insurance::where('car_no','like','%'.$car_no.'%')->where("status",1);
                $count=$insurances->count();
                if($page && $page_size) {
                    $insurances = $insurances->skip($page_size * ($page - 1))->take($page_size)->get();
                }else{
                    $insurances = $insurances->get();
                }
                foreach($insurances as $insurance){
                    $traffic_accident_insurance=$commercial_insurance=new stdClass();
                    if($insurance->insurance_type==1){//交强险
                        $traffic_accident_insurance=InsuranceDetail::where('insurance_id',$insurance->id)->where('type',1)->first();
                        if($traffic_accident_insurance){
                            $traffic_accident_insurance->amount=bcdiv($traffic_accident_insurance->amount,100,2);
                            $traffic_accident_insurance->use_tax=bcdiv($traffic_accident_insurance->use_tax,100,2);
                        }else{
                            $commercial_insurance=$traffic_accident_insurance=new stdClass();
                        }
                    }else if($insurance->insurance_type==2){//商业险
                        $commercial_insurance=InsuranceDetail::where('insurance_id',$insurance->id)->where('type',2)->first();
                        if($commercial_insurance){
                            $commercial_insurance->amount=bcdiv($commercial_insurance->amount,100,2);
                            $its=InsuranceTypes::where('insurance_detail_id',$commercial_insurance->id)->get();
                            $commercial_insurance->its=$its;
                        }else{
                            $commercial_insurance=$traffic_accident_insurance=new stdClass();
                        }
                    }else{//交强险与商业险
                        $traffic_accident_insurance=InsuranceDetail::where('insurance_id',$insurance->id)->where('type',1)->first();
                        $commercial_insurance=InsuranceDetail::where('insurance_id',$insurance->id)->where('type',2)->first();
                        if($traffic_accident_insurance){
                            $traffic_accident_insurance->amount=bcdiv($traffic_accident_insurance->amount,100,2);
                            $traffic_accident_insurance->use_tax=bcdiv($traffic_accident_insurance->use_tax,100,2);
                        }else{
                            $traffic_accident_insurance=new stdClass();
                        }
                        if($commercial_insurance){
                            $commercial_insurance->amount=bcdiv($commercial_insurance->amount,100,2);
                            $its=InsuranceTypes::where('insurance_detail_id',$commercial_insurance->id)->get();
                            $commercial_insurance->its=$its;
                        }else{
                            $commercial_insurance=new stdClass();
                        }
                        
                    }
                    if($insurance->insurance_type==1){
                        $insurance->insurance_name="交强险";
                    }elseif($insurance->insurance_type==2){
                        $insurance->insurance_name="商业险";
                    }else{
                        $insurance->insurance_name="交强险&商业险";
                    }
                    
                    $insurance->traffic_accident_insurance=$traffic_accident_insurance;
                    $insurance->commercial_insurance=$commercial_insurance;
                    $insurance->amount=bcdiv($insurance->amount,100,2);
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('count'=>$count,'insurances'=>$insurances));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      zwh
     * @DateTime:    2016-11-10 14:16:03
     * @Description: 车辆种类、承保险种等列表选项
     */
    public function options(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }
            $iun=InsuranceUseNature::all();
            $ic=InsuranceCompany::all();
            $is=InsuranceSpecies::all();
            $itd=InsuranceTypeDe::all();
            $kr=KickbackRate::where("city_id",$sc_user->shop->city_id)->where("status",1)->get();
            $kr_array=array();
            foreach ($kr as $_k) {
                $kr_array[$_k->id]=$_k;
            }
            $me=MaintenanceEngineers::where('status',1)->select('id','name')->get();
            $sc=SCUser::where('status',1)->select('id','real_name')->get();
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('insurance_use_nature'=>$iun,'insurance_company'=>$ic,'insurance_species'=>$is,'insurance_type_de'=>$itd,'me'=>$me,'sc'=>$sc,'kr'=>$kr_array,'insurance_type'=>Insurance::$insurance_type));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zwh
     * @DateTime:    2016-11-15 10:49:05
     * @Description: 自检
     */
    public function selfCheck(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'car_no' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }

            $insurance=Insurance::where('car_no',Input::get('car_no'))->where("status",1)->orderBy("created_at","desc")->select(array("car_no","engine_number","model","vin","use_nature","purchase_amount","register_time","species","owner"))->first();
            $uci=UserCarInfo::where('car_no',Input::get('car_no'))->where('is_lock',1)->select("car_no",'vin_code')->first();
            $response['result']=array('uci'=>$uci,'insurance'=>$insurance);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "selfCheck", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-04-14 16:10:44
     * @Description: 删除 保险单
     */
    public function deleteInsurance(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
                'username' => 'required',
                'password' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.station_args_error_31001");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $sc_user=$this->verificationSCSUserToken(Input::get("token"),$response);
            if(is_null($sc_user)){
                break;
            }

            $ins=Insurance::find(Input::get("id"));
            if(is_null($ins)||$ins->status!=1){
                $response = Lang::get("scs_error.insurance_notexiet_90015");
                break;
            }

            if($ins->website!=$sc_user->shop_id){
                $response = Lang::get("scs_error.insurance_delete_err_90016");
                break;
            }

            $ai=AcountInsurance::find(Input::get("id"));
            if($ai){
                $response = Lang::get("scs_error.insurance_rechange_exits_90017");
                break;
            }
            // $sc_user->shop_id
            $sc=SCUser::where('user_name',Input::get('username'))->where('password',strtoupper(md5(Input::get('password'))))->where('status',1)->first();
            if(is_null($sc)){
                $response = Lang::get("scs_error.scs_user_not_exiet21009");
                break;
            }
            if($sc->title!=1){
                $response = Lang::get("scs_error.login_user_error_21016");
                break;
            }
            $ins->status=2;
            $ins->save();
            
            $response['result']=array('insurance_id'=>$ins->id);
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "selfCheck", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
}